package com.dsr.util;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author dsr
 * @since 2020-10-17
 */
public class RedisUtil {

    private static final RedisTemplate<String, Object> redisTemplate;

    static {
         redisTemplate = SpringContextUtil.getBean("redisTemplate");
    }
    public static void  setValue(String key,Object value){
        Random random = new Random();
        //[1-2]小时
        int time=random.nextInt(60)+60;
        try {
            redisTemplate.opsForValue().set(key,value,time, TimeUnit.MINUTES);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public static void  setValue(String key,Object value,long time,TimeUnit timeUnit){
        try {
            redisTemplate.opsForValue().set(key,value,time,timeUnit);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static Object getValue(String key){
        Object object=null;
        try {
            object= redisTemplate.opsForValue().get(key);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return object;
    }
    public static void delete(String key){
        try {
            redisTemplate.delete(key);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
